﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SalesSys.WebCore.Authorize
{

    /// <summary>
    /// 用户角色标记,使用WXRoleDataSign定义,只要有给定角色就可以访问，宽松验证，不给定标识只要登录即可
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class UserRoleAuthItemAttribute : AuthorizeAttribute
    {
        public string[] RoleList { get; set; }
        public string RedirectUrl { get; set; }
        /// <summary>
        /// 允许的角色名列表
        /// </summary>
        /// <param name="roles">允许的角色名列表，为null允许任何已登录用户访问</param>
        public UserRoleAuthItemAttribute(params string[] roles)
        {
            RoleList = roles;
        }
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (RoleList == null || RoleList.Length < 1)
            {
                return httpContext.User != null && httpContext.User.Identity != null && httpContext.User.Identity.IsAuthenticated && ClientHelper.ClientInfo != null;
            }
            return RoleList.Any(ClientHelper.IsHaveRole);
            //   FormsAuthentication
            //return base.AuthorizeCore(httpContext);
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (RedirectUrl != null)
            {
              var url=  filterContext.HttpContext.Request.RawUrl;
                filterContext.Result = new RedirectResult(RedirectUrl+"?ReturnUrl="+ HttpUtility.UrlEncode(url), false);
                return;
            }
            base.HandleUnauthorizedRequest(filterContext);
            string url1 = "~/Home/Index";
            filterContext.Result = new RedirectResult(url1);
  
        }
    }
}
